package com.example.cloud.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用hystrix实现服务熔断
 *
 * @author tongyufu
 */
@Slf4j
@Service
public class HelloService {

    @Autowired
    private EurekaClient eurekaClient;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 当此方法报错时，将服务降级到方法helloFallback
     *
     * @return hello
     */
    @HystrixCommand(fallbackMethod = "helloFallback", ignoreExceptions = { NullPointerException.class })
    public String hello() {
        String url = "http://HELLO-SERVICE/hello";
        return restTemplate.getForEntity(url, String.class).getBody();
    }

    /**
     * hello()报错时会调用此方法，此方法必须和主方法在同一个类中，public、protected、private都可以
     *
     * @param e 可选参数，出错时hello()方法会自动传入
     * @return error
     */
    public String helloFallback(Throwable e) {
        System.out.println("异常：" + e.getMessage());
        return "error";
    }

}
